package models

import (
	"ginstudydemo.com/main/dao"
)

// GetSysRoleMenuPerm 获取角色按钮权限列表
func GetSysRoleMenuPerm(codes string) (*[]string, error) {

	var perms []string
	err := dao.Db.Debug().Table("sys_role_menu t1").
		Select("DISTINCT t2.perm").
		Joins("INNER JOIN sys_menu t2 ON t2.id = t1.menu_id").
		Joins("INNER JOIN sys_role t3 ON t3.id = t1.role_id").
		Where("t2.type = '4' AND t2.perm IS NOT NULL AND t3.CODE IN (?)", codes).
		Pluck("t2.perm", &perms).Error

	if err != nil {
		return nil, err
	}
	return &perms, nil
}

// GetMenuIdsByRoleId 获取角色的菜单ID集合
func GetMenuIdsByRoleId(roleId string) (interface{}, error) {

	// SELECT rm.menu_id FROM sys_role_menu rm INNER JOIN sys_menu m ON rm.menu_id = m.id WHERE rm.role_id = ?
	var perms []string
	err := dao.Db.Debug().
		Table("sys_role_menu rm").
		Select("rm.menu_id").
		Joins("INNER JOIN sys_menu m ON rm.menu_id = m.id").
		Where("rm.role_id = ?", roleId).
		Pluck("rm.menu_id", &perms).Error

	if err != nil {
		return nil, err
	}
	return &perms, nil
}

// DelRoleMenuByRoleId 根绝角色id删除角色对应的菜单id
func DelRoleMenuByRoleId(roleId string) error {
	//==>  Preparing: DELETE FROM sys_role_menu WHERE (role_id = ?)
	//==> Parameters: 4(Long)
	err := dao.Db.Debug().Table("sys_role_menu").Where("role_id = ?", roleId).Delete(struct{}{}).Error
	return err
}

// AddRoleMenus 批量增加角色菜单对应数据
func AddRoleMenus(roleId int64, menuIds []int64) error {
	//==>  Preparing: INSERT INTO sys_role_menu ( role_id, menu_id ) VALUES ( ?, ? )
	//==> Parameters: 4(Long), 1(Long)

	var insertData []AddRoleMenusData
	for _, val := range menuIds {
		insertData = append(insertData, AddRoleMenusData{
			RoleId: roleId,
			MenuId: val,
		})
	}

	err := dao.Db.Debug().Table("sys_role_menu").Create(&insertData).Error
	return err
}
